package com.louis.scheduler.support;

import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;


import java.util.Properties;


/**
 * @author Lijun jiang
 * @Date: May 10, 2011
 * @Time: 12:35:58 PM
 */

public class DynamicScheduler extends SchedulerFactoryBean implements InitializingBean {

    private static Scheduler scheduler;

    public DynamicScheduler() {
        setSchedulerName("dynamicScheduler");
        Properties properties = new Properties();
        properties.setProperty("org.quartz.jobStore.tablePrefix", "qrtz_");
        properties.setProperty("org.quartz.jobStore.class", "org.quartz.impl.jdbcjobstore.JobStoreTX");
        properties.setProperty("org.quartz.jobStore.driverDelegateClass", "org.quartz.impl.jdbcjobstore.StdJDBCDelegate");
        setQuartzProperties(properties);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        super.afterPropertiesSet();
        if (scheduler == null) {
            scheduler = (Scheduler) getObject();
        }
    }
    
    public static void schedule(JobDetail jobDetail, Trigger trigger) throws SchedulerException {
        scheduler.scheduleJob(jobDetail, trigger);
    }

    public static void schedule(JobDetailAndTrigger jobDetailAndTrigger) throws SchedulerException {
        scheduler.scheduleJob(jobDetailAndTrigger.getJobDetail(), jobDetailAndTrigger.getTrigger());
    }

    public static void unSchedule(String jobName, String groupName) throws SchedulerException {
        scheduler.deleteJob(jobName, groupName);
    }

    public static JobDetail getJobDetail(String jobName, String groupName) throws SchedulerException {
        return scheduler.getJobDetail(jobName, groupName);
    }

    public static Trigger loadJobTrigger(JobDetail jobDetail) throws SchedulerException {
        return scheduler.getTrigger(jobDetail.getName(), jobDetail.getGroup());
    }
}